package com.tongzhan.upload;

import com.tongzhan.base.Consts;
import com.tongzhan.util.FtpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class UploadController {

    @RequestMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file){
        Map<String, Object> map = new HashMap<>();
        if (file.isEmpty()) {
            map.put("code", 202);
            map.put("message", "文件为空");
            map.put("data", null);
            return map;
        }
        // 获取原文件名称
        String originalFilename = file.getOriginalFilename();
        String fileF = originalFilename.substring(originalFilename.lastIndexOf("."));
        String currentTimeMillis = String.valueOf(System.currentTimeMillis());
        // 生成新的文件名
        String newFileName = currentTimeMillis + UUID.randomUUID() + fileF;

        FtpUtil ftpClient = new FtpUtil();

        // 创建ftp连接
        ftpClient.connectServer();
        try {
            InputStream stream = file.getInputStream();
            String dirName = ftpClient.getDay();
            // 生成服务器当前日期目录
            boolean b = ftpClient.createDir(dirName);
            if(stream != null && b) {
                // ftp上传文件
                boolean result = ftpClient.upload(stream, newFileName, dirName);
                if(result) {
//                    String url= "http://" + Consts.ftpIP + dirName + newFileName;
                    String url=Consts.uploadUrl + dirName + newFileName;
                    Map<String, Object> urlMap = new HashMap<>(1);
                    urlMap.put("url", url);
                    map.put("code", 200);
                    map.put("message", "请求成功");
                    map.put("data", urlMap);
                    return map;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", 202);
        map.put("message", "文件上传失败");
        map.put("data", null);
        return map;
    }
}
